import { Component, OnInit } from '@angular/core'
import { Validators, FormControl, FormBuilder, FormGroup } from '@angular/forms'
import { NzMessageService } from 'ng-zorro-antd'
import { I18NService } from '@core'
import { take } from 'rxjs/operators'
import { RuleTypeTextMap } from '@shared/interfaces/common'
import { PostRiskStoreService } from '../post-risk-store.service'
import { makeAllControlDirty } from 'app/utils/helpers'
import { NewPageAccessor } from '@shared/components/new-page/new-page.interface'
import { IDepositCollection } from '@shared/interfaces/deposit'
import { PostRiskService } from '../../post-risk.service'
import { Router, ActivatedRoute } from '@angular/router'
import { PostRiskScheme, RiskRules, OperateType } from '@shared/interfaces/post-risk-control'
import { postRiskThreshold, postRiskScore } from '../../../../utils/contraints'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { numScale } from 'app/utils/helpers'
import { CurrencyService } from '@shared/services/currency.service'

@Component({
  selector: 'app-tab-edit-rules',
  templateUrl: './tab-edit-rules.component.html',
  styleUrls: ['../../../../shared/styles/table.less'],
})
export class TabEditRulesComponent implements NewPageAccessor, OnInit {
  ruleList: RiskRules[]
  ruleForm: FormGroup
  data: any
  payload: IDepositCollection
  riskRuleControlArray: Array<{
    id: number;
    threshold: string;
    thresholdDesc: string;
    ruleType: string;
    score: string;
    ruleID: string;
    ruleName: string;
    thresholdType?: string;
  }> = []
  type: number
  digital: number
  RuleTypeTextMap = RuleTypeTextMap
  operateType = OperateType
  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private i18n: I18NService,
    private riskStore: PostRiskStoreService,
    private riskService: PostRiskService,
    public route: ActivatedRoute,
    private currencyService: CurrencyService,
  ) {}

  ngOnInit() {
    this.currencyService.getDecimalByCode(this.riskStore.value.currency).subscribe(digital => {
      this.digital = digital
    })
    this.ruleForm = this.fb.group({})
    this.route.queryParams.subscribe(params => {
      this.type = Number(params.type)
    })
    if (this.riskStore.value.ruleLists) {
      this.ruleList = this.riskStore.value.ruleLists
      for (let i = 0; i < this.ruleList.length; i++) {
        this.addControl()
        if (this.ruleList[0].ruleType === '0' || this.ruleList[0].ruleType === '1') {
          this.ruleForm
            .get(this.riskRuleControlArray[i].ruleType)
            .setValue(this.trans(RuleTypeTextMap[this.ruleList[i].ruleType]))
        } else {
          this.ruleForm.get(this.riskRuleControlArray[i].ruleType).setValue(this.ruleList[i].ruleType)
        }
        if (this.ruleList[i].thresholdType === '3') {
          this.ruleList[i].threshold = this.transAmt(this.ruleList[i].threshold, this.digital)
        }
        this.ruleForm.get(this.riskRuleControlArray[i].ruleName).setValue(this.ruleList[i].ruleName)
        this.ruleForm.get(this.riskRuleControlArray[i].ruleID).setValue(this.ruleList[i].ruleID)
        this.ruleForm.get(this.riskRuleControlArray[i].threshold).setValue(this.ruleList[i].threshold)
        this.ruleForm.get(this.riskRuleControlArray[i].score).setValue(this.ruleList[i].score)
        this.ruleForm.get(this.riskRuleControlArray[i].thresholdDesc).setValue(this.ruleList[i].thresholdDesc)
      }
      return
    }
    if (this.type === this.operateType.copy || this.type === this.operateType.edit) {
      // 复制方案
      const tmp = this.riskStore.value
      this.riskService.getOne(tmp.schemeCode).subscribe((postRiskScheme: PostRiskScheme) => {
        this.ruleList = postRiskScheme.ruleList
        for (let i = 0; i < this.ruleList.length; i++) {
          this.addControl()
          if (this.ruleList[i].thresholdType === '3') {
            this.ruleList[i].threshold = this.transAmt(this.ruleList[i].threshold, this.digital)
          }
          this.ruleForm.get(this.riskRuleControlArray[i].ruleName).setValue(this.ruleList[i].ruleName)
          this.ruleForm.get(this.riskRuleControlArray[i].ruleID).setValue(this.ruleList[i].ruleID)
          this.ruleForm.get(this.riskRuleControlArray[i].threshold).setValue(this.ruleList[i].threshold)
          this.ruleForm.get(this.riskRuleControlArray[i].score).setValue(this.ruleList[i].score)
          this.ruleForm
            .get(this.riskRuleControlArray[i].ruleType)
            .setValue(this.trans(RuleTypeTextMap[this.ruleList[i].ruleType]))
          this.ruleForm.get(this.riskRuleControlArray[i].thresholdDesc).setValue(this.ruleList[i].thresholdDesc)
          this.ruleForm.get(this.riskRuleControlArray[i].thresholdType).setValue(this.ruleList[i].thresholdType)
        }
        return
      })
    } else {
      this.riskService
        .getRules()
        .pipe(take(1))
        .subscribe(data => {
          if (data) {
            this.ruleList = data
            for (let i = 0; i < this.ruleList.length; i++) {
              this.addControl()
              if (this.ruleList[i].thresholdType === '3') {
                this.ruleList[i].threshold = this.transAmt(this.ruleList[i].threshold, this.digital)
              }
              this.ruleForm.get(this.riskRuleControlArray[i].ruleName).setValue(this.ruleList[i].ruleName)
              this.ruleForm.get(this.riskRuleControlArray[i].threshold).setValue(this.ruleList[i].threshold)
              this.ruleForm.get(this.riskRuleControlArray[i].score).setValue(this.ruleList[i].score)
              this.ruleForm
                .get(this.riskRuleControlArray[i].ruleType)
                .setValue(this.trans(RuleTypeTextMap[this.ruleList[i].ruleType]))
              this.ruleForm.get(this.riskRuleControlArray[i].thresholdDesc).setValue(this.ruleList[i].thresholdDesc)
              this.ruleForm.get(this.riskRuleControlArray[i].ruleID).setValue(this.ruleList[i].ruleID)
            }
          }
        })
    }
  }

  // 获取列表中的表单
  addControl() {
    const id = this.riskRuleControlArray.length > 0 ? this.riskRuleControlArray.length : 0
    const rules = {
      id,
      threshold: `threshold${id}`,
      score: `score${id}`,
      ruleType: `ruleType${id}`,
      thresholdDesc: `thresholdDesc${id}`,
      ruleID: `ruleID${id}`,
      ruleName: `ruleName${id}`,
      thresholdType: `thresholdType${id}`,
    }
    this.ruleForm.addControl(`ruleID${id}`, new FormControl(''))
    this.ruleForm.addControl(
      `threshold${id}`,
      new FormControl('', [Validators.required, Validators.pattern(postRiskThreshold)]),
    )
    this.ruleForm.addControl(
      `score${id}`,
      new FormControl('', [Validators.required, Validators.pattern(postRiskScore)]),
    )
    this.ruleForm.addControl(`thresholdDesc${id}`, new FormControl(''))
    this.ruleForm.addControl(`ruleType${id}`, new FormControl(''))
    this.ruleForm.addControl(`ruleName${id}`, new FormControl(''))
    this.ruleForm.addControl(`thresholdType${id}`, new FormControl(''))
    this.riskRuleControlArray.push(rules)
  }

  checkValid(): boolean {
    const valid = this.ruleForm.valid
    if (!valid) {
      makeAllControlDirty(this.ruleForm)
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    } else {
      this.pushDataToStore()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    }
    return valid
  }

  pushDataToStore(): void {
    // 获取数据
    const ruleLists = []
    const ruleList = []
    this.riskRuleControlArray.forEach((item, index) => {
      const rule = {
        ruleType: this.ruleForm.get(`ruleType${index}`).value,
        thresholdDesc: this.ruleForm.get(`thresholdDesc${index}`).value,
        ruleName: this.ruleForm.get(`ruleName${index}`).value,
        ruleID: this.ruleForm.get(`ruleID${index}`).value,
        threshold: this.ruleForm.get(`threshold${index}`).value,
        score: Number(this.ruleForm.get(`score${index}`).value),
        thresholdType: this.ruleForm.get(`thresholdType${index}`).value,
      }
      const rules = {
        ruleID: this.ruleForm.get(`ruleID${index}`).value,
        threshold: this.ruleForm.get(`threshold${index}`).value,
        score: Number(this.ruleForm.get(`score${index}`).value),
        thresholdType: this.ruleForm.get(`thresholdType${index}`).value,
      }
      ruleList.push(rules)
      ruleLists.push(rule)
    })
    const tmp = this.riskStore.value
    Object.assign(tmp, { ruleList, ruleLists })
    this.riskStore.setValue(tmp)
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  transAmt(value: number, digital: number = 0) {
    const amt = numScale(value, -digital).toFixed(digital)
    return amt
  }
}
